/**
 * 函数节流的工具函数
 * @author 莫若省
 * @param func  要节流的函数
 * @param delay 触发频率
 */
export const throttle = <T extends (...args: any[]) => void, This>(
  func: T,
  delay: number,
): ((this: This, ...args: Parameters<T>) => void) => {
  let timer: ReturnType<typeof setTimeout> | null = null;
  let lastArgs: Parameters<T> | null = null;

  return function (this: This, ...args: Parameters<T>): void {
    if (!timer) {
      func.apply(this, args);
      lastArgs = null;
      timer = setTimeout(() => {
        timer = null;
        if (lastArgs) {
          func.apply(this, lastArgs);
          lastArgs = null;
        }
      }, delay);
    } else {
      lastArgs = args;
    }
  };
};
/**
 * 防抖函数
 * @author 莫若省
 * @param func  要防抖的函数
 * @param delay 触发延时
 */
export const debounce = <T extends (...args: any[]) => void, This>(
  func: T,
  delay: number,
): ((this: This, ...args: Parameters<T>) => void) => {
  let timer: ReturnType<typeof setTimeout> | null = null;

  return function (this: This, ...args: Parameters<T>): void {
    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
};
